from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.utils.html import format_html
from django.utils.safestring import mark_safe
from .models import User, UserProfile, LoginHistory


@admin.register(User)
class UserAdmin(BaseUserAdmin):
    """
    用户管理界面
    """
    list_display = (
        'username', 'email', 'get_full_name', 'is_active', 
        'is_staff', 'is_superuser', 'last_login', 'created_at'
    )
    list_filter = (
        'is_active', 'is_staff', 'is_superuser', 
        'theme_preference', 'language_preference', 'created_at'
    )
    search_fields = ('username', 'email', 'bio')
    readonly_fields = ('id', 'created_at', 'updated_at', 'last_login')
    ordering = ('-created_at',)
    
    fieldsets = (
         ('基本信息', {
             'fields': ('username', 'email')
         }),
        ('个人资料', {
            'fields': ('avatar', 'bio')
        }),
        ('偏好设置', {
            'fields': ('theme_preference', 'language_preference')
        }),
        ('权限设置', {
            'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')
        }),
        ('重要日期', {
            'fields': ('last_login', 'created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
        ('系统信息', {
            'fields': ('id',),
            'classes': ('collapse',)
        })
    )
    
    add_fieldsets = (
        ('创建用户', {
            'classes': ('wide',),
            'fields': ('username', 'email', 'password1', 'password2')
        }),
    )
    
    def get_full_name(self, obj):
        """显示完整姓名"""
        if obj.first_name and obj.last_name:
            return f'{obj.first_name} {obj.last_name}'
        elif obj.first_name:
            return obj.first_name
        elif obj.last_name:
            return obj.last_name
        else:
            return obj.username
    get_full_name.short_description = '姓名'


@admin.register(UserProfile)
class UserProfileAdmin(admin.ModelAdmin):
    """
    用户配置管理界面
    """
    list_display = (
        'user', 'editor_theme', 'editor_font_size', 
        'auto_save_enabled', 'auto_save_interval'
    )
    list_filter = (
        'editor_theme', 'auto_save_enabled', 
        'editor_font_size', 'auto_save_interval'
    )
    search_fields = ('user__username', 'user__email')
    readonly_fields = ('user',)
    
    fieldsets = (
        ('编辑器设置', {
            'fields': ('editor_theme', 'editor_font_size', 'editor_font_family')
        }),
        ('自动保存', {
            'fields': ('auto_save_enabled', 'auto_save_interval')
        }),
        ('用户关联', {
            'fields': ('user',),
            'classes': ('collapse',)
        })
    )
    
    def get_queryset(self, request):
        """优化查询性能"""
        return super().get_queryset(request).select_related('user')


@admin.register(LoginHistory)
class LoginHistoryAdmin(admin.ModelAdmin):
    """
    登录历史管理界面
    """
    list_display = (
        'user', 'ip_address', 'user_agent_short', 
        'is_successful', 'login_time'
    )
    list_filter = ('is_successful', 'login_time')
    search_fields = ('user__username', 'user__email', 'ip_address')
    readonly_fields = ('user', 'ip_address', 'user_agent', 'is_successful', 'login_time')
    ordering = ('-login_time',)
    
    def user_agent_short(self, obj):
        """显示简短的用户代理信息"""
        if len(obj.user_agent) > 50:
            return obj.user_agent[:50] + '...'
        return obj.user_agent
    user_agent_short.short_description = '用户代理'
    
    def get_queryset(self, request):
        """优化查询性能"""
        return super().get_queryset(request).select_related('user')
    
    def has_add_permission(self, request):
        """禁止手动添加登录历史"""
        return False
    
    def has_change_permission(self, request, obj=None):
        """禁止修改登录历史"""
        return False
